<?php
	/**
	 * <version greek="beta" major="1" minor="0">Cochin Splash Hen</version>
	 * <author email="njones@art-k-tec.com">Nika Jones</author>
	 * <copyright start="2007">Art-k-tec Systems, LLC</copyright>
	 * <license type="Apache2.0" href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</license>
	 */
	
	/**
	* <summary>
	*	Handles the hashing for directories. To make sure that you don't have too many files
	*	in any one directory. Is a singleton that things should go through
	* </summary>
	*/
	class bDirectoryHash {
	
		private static $nMajor =1;
		private static $nMinor =0;
		private static $sRevision ="0000";
		
		const WORD_AS_NUMBER 	=1;
		const BASIC				=2;
		const HASH				=3;
		const DEFAULT_HASH		=4;
		const DEFAULT_LENGTH    =2;
		
		const _SLASH            =DIRECTORY_SEPARATOR;

		private static $oInstance =null;
		
		public function GetInstance() {
			
			if(self::$oInstance ==null) {
				
				self::$oInstance =new bDirectoryHash();
				$oInstance =self::$oInstance;
			} else {
				
				$oInstance =self::$oInstance;
			}
			
			return $oInstance;
		}
		
		public static function version() { return self::$nMajor.'.'.self::$nMinor.'.'.self::$sRevision; }
		
		public function Hash($sFilename, $sType =self::BASIC, $nLength =self::DEFAULT_LENGTH) {
			
			if(!isset($this)) {
				
				$oInstance =self::GetInstance();
			} else {
				
				$oInstance =$this;
			}
			
			switch($sType) {
				
				case self::DEFAULT_HASH:
					$sHashDirectory =$oInstance->DefaultProvider($sFilename, $nLength).self::_SLASH;
				break;
				
				case self::BASIC:
					$sHashDirectory =$oInstance->BasicProvider($sFilename, $nLength).self::_SLASH;
				break;
				
				case self::HASH:
					$sHashDirectory =$oInstance->HashProvider($sFilenamem, $nLength).self::_SLASH;
				break;
				
				case self::WORD_AS_NUMBER:
					$sHashDirectory =$oInstance->WordAsNumberProvider($sFilename, $nLength).self::_SLASH;
				break;
			}
			
			return $sHashDirectory;
		}
		
		///<summary>
		///		Provides the hash inteface for the directory hash using the
		///		the file name and the first 2-4 characters. (recommended)
		///</summary>
		private function DefaultProvider($sFilename, $nIndex =2) {
			while(strlen($sFilename) < $nIndex) {
				
				$sFilename .=$sFilename;
			}
			
			return substr($sFilename, 0, $nIndex);
		}
		
		///<summary>
		///		Provides the hash inteface for the directory hash using the hash of
		///		the file name and the first 2-4 characters of the hash.
		///</summary>
		private function HashProvider($sFilename, $nIndex =2) {
			return str_replace('.', '_', substr(crypt($sFilename, "bd"), 2, $nIndex));
		}
		
		private function BasicProvider($sFilename, $nIndex =2) {
			return substr(preg_replace('/[^A-Z0-9]/i', '', $sFilename), 0, $nIndex);
		}
		
		private function WordAsNumberProvider($sFilename) {
			$n =1;
			
			$a =str_split($sFilename);
			foreach($a as $s) { $n +=ord($s); }
			
			$n =ceil($n/4);
			return $n;
		}
	}	
?>